package com.sd.chat.web;

import java.io.File;
import java.io.IOException;

import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


// A anotation MultipartConfig permite configurar onde colocar o ficheiro, e o tamanho maximo
// de Upload.

@SuppressWarnings("serial")


@MultipartConfig(location = WebConfigs.uploadWebPath, maxFileSize = 10485760L) // 10MB.

@WebServlet(urlPatterns = { "/FileUploadServlet" })
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        MultipartMap map = new MultipartMap(request, this); // Processa os ficheiros de upload
        String text = map.getParameter("name");
        File file = map.getFile("file"); // Devolve o ficheiro depois de feito o upload.
        //file.renameTo(new File(WebConfigs.uploadWebPath+"\\"+text));
        // Now do your thing with the obtained input.
        System.out.println("Text: " + text);
        System.out.println("File: " + file);
        
        PrintWriter out = response.getWriter();
        
        out.write(file.toString());

        //request.getRequestDispatcher("/upload_ok.jsp").forward(request, response);
    }

}